package org.yjh.service.lmpl;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yjh.dao.CollectionDao;
import org.yjh.dao.GoodsDao;
import org.yjh.dao.UserDao;
import org.yjh.pojo.Collections;
import org.yjh.pojo.Goods;
import org.yjh.pojo.User;
import org.yjh.service.LoginService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class LoginServiceIMPI implements LoginService {
    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private CollectionDao collectionDao;

    @Override
    public String analysisCode(String code, HttpServletRequest req) {
        // 判断验证码
        Cookie[] cookies = req.getCookies();
        String codeValue = "";
        for (Cookie c : cookies) {
            if(c.getName().equals("code")){
                codeValue = c.getValue();
            };
        }
        // 大小写处理
        String lcode = code.toLowerCase();
        String tolCode = codeValue.toLowerCase();
        Map map = new HashMap<>();
        if(lcode.equals(tolCode)){
            map.put("code","1");
            return  JSONObject.toJSONString(map);
        }
        map.put("code","0");
        return  JSONObject.toJSONString(map);
    }

    @Override
    public User analysisUser(String uname,String password) {
        // 判断登录 查询用户密码
        User user = userDao.getLogin(uname,password);
        System.out.println("查询的user"+user);
        if(user!=null){
            if (uname.equals(user.getUname()) && password.equals(user.getPassword())) {
                // 存cookie
                String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
                //生成随机角标【随机生产数去取str字符串的某个索引】
                Random ran = new Random();
                String cookie = "";
                for (int i = 1; i <= 4; i++) {
                    int index = ran.nextInt(str.length());//在长度范围内产生一个随机的数
                    char ch = str.charAt(index);//从随机数获取字符
                    cookie += ch;
                }
                // 数据库存cookie
                userDao.setCookie(cookie, user.getUid());
                // 查询user信息不包括密码
                User yesUser = userDao.getUser(user.getUid());

                return yesUser; // 成功返回
            }
        }
            return user;

    }

    @Override
    public String registeredUser(User u) {
        // 查询用户名是否被注册
        User user = userDao.getUserByName(u.getUname());
        System.out.println("传过来的信息："+u);
        if(user!=null){
            // 被注册返回
            Map map = new HashMap<>();
            map.put("registered","0");
            System.out.println("返回的信息："+JSONObject.toJSONString(map));
            return  JSONObject.toJSONString(map);
        }else{
            // 没被注册进行注册
            userDao.setUser(u);
            // 返回成功的信息
            Map map = new HashMap<>();
            map.put("registered","1");
            System.out.println("返回的信息："+JSONObject.toJSONString(map));
            return  JSONObject.toJSONString(map);
        }
    }

    @Override
    public List<Goods> getListGoods(String gtype) {
        System.out.println("@@@@@");
        if ("最新发布".equals(gtype)){
            List<Goods> listGoods = goodsDao.getListGoodsAll(); //获取7天内的数据
            System.out.println("@@@@@"+listGoods.get(0));
            return listGoods;
        }else{
            List<Goods> listGoods = goodsDao.getListGoods(gtype);
            return listGoods;
        }

    }

    @Override
    public int isRoot(User user) {

        User u = userDao.getUser(user.getUid());
        return u.getUtype();
    }

    @Override
    public List<Goods> getGoodsByGname(Goods g) {
        return goodsDao.getGoodsByGname(g);
    }

    @Override
    public List<User> getUserAsConditions(User u) {
        return userDao.getUserAsConditions(u);
    }

    @Override
    public List<Goods> getGoodsAsConditions(Goods g) {
        // 根据uid查询用户的类型【是否管理员】
        User user = userDao.getUser(g.getUid());
        // 是管理员查询全部信息
        if(user.getUtype() == 1){
            System.out.println("1111111");
            return goodsDao.getGoodsAsConditions(g);
        }else{
            // 非管理员查看用户单人的信息
            System.out.println("2222222");
            return goodsDao.getGoodsAsConditionsOfUser(g);
        }

    }

    @Override
    public void deleteUserCookie(User u) {
        userDao.setCookie("",u.getUid());
    }

    @Override
    public Goods getGoodsAsId(Goods g) {
        return goodsDao.getGoodsAsId(g);
    }

    @Override
    public void deleteGoods(User u,String choose) {

        // 将数据进行分割
        System.out.println("分割@@@");
        String[] s = choose.split("&choose=");

        // 根据s[]查询gid的url路径【先获取url再删除消息】
        List<Goods> gids = goodsDao.getGids(s);

        for (Goods gid : gids) {
            // 判断该商品是否收藏或购买【如果没有才能删除】
            Collections c = collectionDao.selectCollectionsByGID(gid.getGid());
            System.out.println("收藏的c:"+c);
            if(c!=null){
                // 有被收藏 修改商品为隐藏状态，不可见
                goodsDao.setHidden(gid.getGid());
            }else{
                // 没被收藏可以删除
                // 根据uid对choose分割出来的gid进行删除
                goodsDao.deleteGoods(u,gid.getGid());
                // 删除对应照片
                String url = "D:\\高级语言笔记\\二手平台\\school_platform\\src\\assets\\";
                File file = new File( url+gid.getUrl());
                if (file.exists()) {
                    file.delete();
                }
            }
        }



//        // 删除对应的照片
//        for (Goods gid : gids) {
//            String url = "D:\\高级语言笔记\\二手平台\\school_platform\\src\\assets\\";
//            File file = new File( url+gid.getUrl());
//            if (file.exists()) {
//                file.delete();
//            }
//        }

    }

    @Override
    public void setGoods(Goods g,String url) {
        // 设置当前date  yyyy-mm-dd
        Date date = new Date();
        SimpleDateFormat dtf = new SimpleDateFormat("yyyy-MM-dd");
        String last_time = dtf.format(date);

        g.setDate(last_time);
        g.setUrl(url);

        goodsDao.setGoods(g);
    }

    @Override
    public void upDateGoods(Goods g) {
        goodsDao.upDateGoods(g);
    }

    @Override
    public String setCollections(Collections c, boolean collection){
        System.out.println("conllections："+collection);
        System.out.println("Conllections："+c);
        if(collection){
            collectionDao.insetCollections(c);

        }else{
            collectionDao.delCollections(c);
        }
        return "1";
    }

    @Override
    public Collections selectCollections(Collections c) {
        return collectionDao.selectCollections(c);
    }

    @Override
    public List<Goods> getGoodsForCollections(Goods g) {
        return goodsDao.getGoodsForCollections(g);
    }
}
